﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Api.Model;
using System.Linq;

namespace Api.Web.Tests
{
    [TestClass]
    public class Add
    {
        private Db db = Db.Current;
        [TestMethod]
        public void AddExist()
        {
            //ok
            //主要說明，就算數據庫當前已經存在的記錄只要add了，只要不會滾還是會添加的
            var list = db.Projects.Take(2);
            db.Projects.AddRange(list); //addrange
            var num = db.SaveChanges();
            Assert.AreEqual(num, list.Count());
        }

        [TestMethod]
        public void AddExist2()
        {
            //ok
            var list = db.Projects.Take(2);
            foreach (var item in list)
                db.Projects.Add(item); //add
            var num = db.SaveChanges();
            Assert.AreEqual(num, list.Count());
        }

        [TestMethod]
        public void Add3()
        {
            //ok
            //只修改這個數據的狀態也是可以的
            var list = db.Projects.Take(2);
            foreach (var item in list)
                db.Entry(item).State = System.Data.Entity.EntityState.Added;

            var num = db.SaveChanges();
            Assert.AreEqual(num, list.Count());
        }

        /////////////////////error,有數據格式錯誤時，事務會回滾//////////////////////////////
        
        [TestMethod]
        public void Add4()
        {
            //error
            //測試一下transaction吧，故意弄一個錯誤數據
            var list = db.Projects.Take(2);
            db.Projects.AddRange(list);
            db.Projects.Add(new Project() { UpdateDate = DateTime.MinValue });
            var num = db.SaveChanges();
            Assert.AreEqual(num, 1 + list.Count());
        }

        #region 跨方法的事務
        [TestMethod]
        public void Add5()
        {
            //測試跨方法下的transaction
            var list = db.Projects.Take(2);
            db.Projects.AddRange(list);
            testAdd();
            var num = db.SaveChanges();
            Assert.AreEqual(num, 1 + list.Count());
        }

        public void testAdd()
        {
            db.Projects.Add(new Project() { UpdateDate = DateTime.MinValue });
        }
        #endregion
    }
}
